<template>
  <!-- 页面-编辑规则 -->
  <div class="sidelip-box">
    <Form :model="modelForm" ref="ruleForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="90">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none;">
          <Form-item prop="code" :label="$t('module.dataPermission.ruleCode')">
            <Input
              v-model.trim="modelForm.code"
              :placeholder="$t('module.dataPermission.warning.enterRuleCode')"
              :disabled="ruleId != ''"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border: none;">
          <Form-item prop="name" :label="$t('module.dataPermission.ruleName')">
            <Input
              v-model="modelForm.name"
              :placeholder="$t('module.dataPermission.warning.enterRuleName')"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none;">
          <Form-item prop="target" :label="$t('module.dataPermission.shieldingObject')">
            <Select v-model="modelForm.target">
              <Option v-for="obj in objectList" :value="obj.vsiKey" :key="obj.vsiKey">{{ obj.vsiValue }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border: none;">
          <Form-item prop="level" :label="$t('module.dataPermission.controlLevel')">
            <Select v-model="modelForm.level" :disabled="ruleId != ''">
              <Option v-for="level in controlLevelList" :value="level.intKey" :key="level.vsiKey">{{
                level.vsiValue
              }}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
    </Form>
    <rule-assign-dimension
      :tenantCode="tenantCode"
      :permissionRule="permissionRule"
      :ruleCode="ruleCode"
      @change="onDimensionChange"
    />
  </div>
</template>
<script>
import valueSetAPI from "@/api/valueSetAPI.js";
import dataPermissionAPI from "@/api/dataPermissionAPI.js";
import locales from "./locales.js";
import RuleAssignDimension from "./RuleAssignDimension.vue";
import { codeReg } from "@/const.js";


export default {
  name: "rule-edit",
  mixins: [locales],
  components: { RuleAssignDimension },
  props: {
    tenantCode: { type: String, required: true },
    permissionRule: {
      type: Object,
      default() {
        return null;
      }
    },
    ruleCode: {
      type: String,
      default() {
        return "";
      }
    },
    ruleId: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    const validateRuleCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.dataPermission.warning.enterRuleCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const validateLevel = (rule, value, callback) => {
      if (value == 0) {
        callback(new Error(this.$t("module.dataPermission.warning.enterControlLevel")));
      }
      callback();
    };
    return {
      // 保存初始数据
      initData: {
        enabled: "",
        dimensionList: [],
        dimensionCodeList: []
      },
      // 标识当前是否是搜索查询
      isSearch: "",
      //取消选中的有效维度
      cancelSelectDimension: [],
      // 暂存维度的数据
      // modelFormDimension: [],
      modelForm: {
        tenantCode: this.tenantCode,
        id: "",
        code: "",
        name: "",
        target: "",
        level: 0,
        enabled: 1
      },
      rule: {
        code: [{ validator: validateRuleCode, trigger: "blur", required: true }],
        name: [
          {
            required: true,
            message: this.$t("module.dataPermission.warning.enterRuleName"),
            trigger: "blur"
          }
        ],
        target: [
          {
            required: true,
            message: this.$t("module.dataPermission.warning.enterShieldingObject"),
            trigger: "change"
          }
        ],
        level: [
          {
            validator: validateLevel,
            required: true,
            trigger: "change"
          }
        ]
      },
      objectList: [],
      controlLevelList: [],
      assignedDimensionList: [],
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {},
  created: function () {
    if (this.ruleId) {
      this.$emit("SetTitle", this.$t("module.dataPermission.editRule"));
    } else {
      this.$emit("SetTitle", this.$t("module.dataPermission.createRule"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  mounted: function () {
    this.init();
  },
  methods: {
    init() {
      if (this.permissionRule) {
        this.modelForm = Object.assign({}, this.permissionRule);
        // 保存初始状态
        this.initData.enabled = this.permissionRule.enabled;
        // 保存初始选中数据
        this.initData.dimensionCodeList = [].concat(this.permissionRule.dimensionCodeList);
        // this.initData.dimensionCodeList = this.permissionRule.dimensionCodeList;
      }
      this.initObject();
      this.initControlLevel();
    },
    // 保存、修改
    saveOrUpdate() {
      this.actions[0].loading = true;
      dataPermissionAPI
        .updateRuleAndDimension(this.modelForm)
        .then(response => {
          this.actions[0].loading = false;
          const content = this.modelForm.id
            ? this.$t("module.dataPermission.warning.updateSuccessfully")
            : this.$t("module.dataPermission.warning.createRuleSuccessfully");
          this.$message.success({
            content: content,
            duration: 3
          });
          this.$emit("Close", true);
        })
        .catch(data => {
          this.actions[0].loading = false;
        });

      // if (this.modelForm.id) {
      //   dataPermissionAPI
      //     .updateRuleAndDimension(this.modelForm)
      //     .then(response => {
      //       this.actions[0].loading = false;
      //       this.$message.success({
      //         content: this.$t("module.dataPermission.warning.updateSuccessfully"),
      //         duration: 3
      //       });
      //       this.$emit("Close", true);
      //     })
      //     .catch(data => {
      //       this.actions[0].loading = false;
      //     });
      // } else {
      //   dataPermissionAPI
      //     .updateRuleAndDimension(this.modelForm)
      //     .then(response => {
      //       this.actions[0].loading = false;
      //       this.$message.success({
      //         content: this.$t("module.dataPermission.warning.createRuleSuccessfully"),
      //         duration: 3
      //       });
      //       this.$emit("Close", true);
      //     })
      //     .catch(data => {
      //       this.actions[0].loading = false;
      //     });
      // }
    },
    // 获取取消选择的数据
    getCancelDimension() {
      // 取消选中的数据（包括有效无效）
      let allCancelDimension = [];
      // 取消选中的数据（只包括有效）
      this.cancelSelectDimension = [];
      // 最新选中的维度
      let selection = this.modelForm.dimensionCodeList;
      // 所有维度数据
      let allDimension = this.initData.dimensionList;
      allDimension.filter(item => {
        // 初始维度中的选中的维度
        if (item._checked) {
          // 选中维度在初始维度中未存在，则代表维度已被取消，并且该取消的维度为有效维度
          // if (selection.indexOf(item.dimensionCode) == -1 && item.enabled == 1) {
          //   this.cancelSelectDimension.push(item);
          // }
          if (selection.indexOf(item.dimensionCode) == -1) {
            allCancelDimension.push(item.dimensionCode);
            if (item.enabled == 1) {
              this.cancelSelectDimension.push(item);
            }
          }
        }
      });
      // 标识当前是否是搜索查询：如果是搜索查询才调用此方法去处理“查询的数据进行取消或新增时，原来选择的数据会被置空”问题
      if (this.isSearch) {
        // 参数1为选中数据，参数2为取消的数据
        this.cancelOrAdd(selection, allCancelDimension);
      }
    },
    // 当针对查询的数据进行取消或新增时，原来选择的数据会被置空，因此把新数据与原数据进行合并去重处理
    cancelOrAdd(selection, allCancelDimension) {
      // 原来的选中数据
      let dimensionCodeList = this.initData.dimensionCodeList;
      // 如存在新增数据
      if (selection.length != 0) {
        let data = dimensionCodeList.concat(selection);
        dimensionCodeList = Array.from(new Set(data));
      }
      // 如存在取消数据
      if (allCancelDimension.length != 0) {
        dimensionCodeList.map((item, index) => {
          if (allCancelDimension.indexOf(item) != -1) {
            dimensionCodeList.splice(index, 1);
          }
        });
      }
      this.modelForm.dimensionCodeList = dimensionCodeList;
      // this.modelFormDimension = dimensionCodeList;
    },
    save() {
      this.getCancelDimension();
      // this.modelForm.dimensionCodeList = this.modelFormDimension;
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          // 初始状态为有效
          if (this.initData.enabled == 1) {
            let warningText;
            if (this.modelForm.enabled == 0) {
              // 更改为无效时的提示
              warningText = this.$t("module.dataPermission.warning.disabledataPolicy");
            } else if (this.cancelSelectDimension.length != 0) {
              // 取消分配的有效维度的提示
              let cancelDimension = [];
              this.cancelSelectDimension.map(item => {
                cancelDimension.push(item.dimensionName);
              });
              warningText =
                this.$t("module.dataPermission.warning.cancelDimension") + "\n" + "[" + cancelDimension + "]";
            }
            if (warningText) {
              // 删除提示级别：更改为无效-普通。取消分配的有效维度-严重
              this.$confirm
                .swarning(warningText)
                .then(() => {
                  this.saveOrUpdate();
                })
                .catch(_ => _);
            } else {
              this.saveOrUpdate();
            }
          } else {
            this.saveOrUpdate();
          }
        }
      });
    },
    // 初始化适用对象
    initObject() {
      valueSetAPI.getValueSetByCode("SYS_DATA_AUTH_OBJECT").then(data => {
        this.objectList = data;
      });
    },
    // 初始化控制层级
    initControlLevel() {
      valueSetAPI.getValueSetByCode("SYS_DATA_AUTH_LEVEL").then(data => {
        this.controlLevelList = data.map(level => {
          level.intKey = Number(level.vsiKey);
          return level;
        });
      });
    },
    onDimensionChange(list, dimensionList, isSearch) {
      // 保存获取到的维度数据
      this.initData.dimensionList = dimensionList;
      // 标识当前是否是搜索查询
      this.isSearch = isSearch;
      // 分配的维度
      this.modelForm.dimensionCodeList = list.map(dimension => {
        return dimension.dimensionCode;
      });
    }
  }
};
</script>
